package lsl.leetCode.year2023.test0125;


import lsl.leetCode.test1222.ListNode;

public class test02 {
    public static void main(String[] args) {
        //先创建节点
        ListNode listNode1 = new ListNode(9);
        ListNode hero2 = new ListNode(9);
        ListNode hero3 = new ListNode(9);
        ListNode hero4 = new ListNode(9);
        ListNode hero5 = new ListNode(9);
        ListNode hero6 = new ListNode(9);
        ListNode listNode2 = new ListNode(9);
        ListNode hero7 = new ListNode(9);
        ListNode hero8 = new ListNode(9);
        ListNode hero9 = new ListNode(9);
        //创建单链表
        listNode1.next = hero2;
        hero2.next = hero3;
        hero3.next = hero4;
        hero4.next = hero5;
        hero5.next = hero6;


        //创建单链表
        listNode2.next = hero7;
        hero7.next = hero8;
        hero8.next = hero9;
        addTwoNumbers(listNode1, listNode2);
    }

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        //tail代表当前节点指针
        ListNode head = null, tail = null;
        int carry = 0;
        while (l1 != null || l2 != null) {
            int n1 = l1 != null ? l1.val : 0;
            int n2 = l2 != null ? l2.val : 0;
            int sum = n1 + n2 + carry;
            if (head == null) {
                head = tail = new ListNode(sum % 10);
            } else {
                //下一个节点
                tail.next = new ListNode(sum % 10);
                //指针移动到下个节点
                tail = tail.next;
            }
            carry = sum / 10;
            if (l1 != null) {
                l1 = l1.next;
            }
            if (l2 != null) {
                l2 = l2.next;
            }
        }
        if (carry > 0) {
            tail.next = new ListNode(carry);
        }
        return head;
    }
}
